package com.dc.free.db.service;

import java.util.Date;

import com.dc.free.db.model.CBidding;
import com.dc.free.db.model.CGoods;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class CBiddingService {

	static CBidding dao = CBidding.dao;
	
	/**
	 * 活动竞价纪录
	 * @param actionId
	 * @param goodsId
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public static Page<Record> list(String actionId, String goodsId, int pageNumber, int pageSize) {
		return Db.paginate(pageNumber, pageSize, 
				"select no, price, time", 
				"from c_bidding b inner join c_user u on b.user_id = u.id and b.action_id = ? and b.goods_id = ? order by price desc", 
				actionId, goodsId);
	}
	
	/**
	 * 活动最高竞价
	 * @param actionId
	 * @param goodsId
	 * @return
	 */
	public static CBidding getMaxPriceCBidding(String actionId, String goodsId) {
		return dao.findFirst("select b.* from c_bidding b where b.goods_id = ? and b.action_id = ? order by time desc limit 1", 
				goodsId, actionId);
	}

	/**
	 * 添加竞拍纪录
	 * @param goodsId
	 * @param userId
	 * @param price
	 * @return
	 */
	public static synchronized boolean insert(String goodsId, String userId, int price) {
		CGoods goods = CGoodsService.getGoods(goodsId);
		CBidding bidding = getMaxPriceCBidding(goods.getActionId(), goodsId);
		
		if(price < goods.getPrice()+goods.getIncrease()) return false;
		if(bidding != null && bidding.getPrice()!=null && price < bidding.getPrice()+goods.getIncrease()) return false;
		if((price-goods.getPrice()) % goods.getIncrease()!=0) return false;
		
		bidding = new CBidding();
		bidding.setId(HashKit.generateSaltForSha256());
		bidding.setActionId(goods.getActionId());
		bidding.setGoodsId(goodsId);
		bidding.setUserId(userId);
		bidding.setPrice(price);
		bidding.setTime(new Date());
		
		return bidding.save();
	}
	
}
